import { Form } from '@ant-design/compatible';
import AuthComponent from '@/components/Authorized/AuthComponent';
import '@ant-design/compatible/assets/index.css';
import { DatePicker, Radio,Input,Select} from 'antd';
import React, { useState, useCallback, useRef ,  useEffect} from 'react';
import ProTable from '@ant-design/pro-table';
import { useRequest } from '@umijs/hooks';
import ListofDetails from './components/ListofDetail';
import { queryFlightTable,queryCityInfo } from './service';
import moment from 'moment';
import styles from './index.less';
const { Option } = Select;

let hiddenData = null
const TableList = () => {
  const { data:selectData } = useRequest(queryCityInfo);
  const [createModalVisible, handleModalVisible] = useState(false);
  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 360);
    } else {
      controlH(document.body.clientHeight - 470);
    }
  }, [isCollapse])
  const actionRef = useRef();
  const ref = useRef();
  // const [inited, setInited] = useState(true)
  // // 日历限制
  // const [dates, setDates] = useState([]);
  const [flightId, setflightId] = useState('0');//航班id
  const [getflightStatus,setHlightStatus]=useState('')//航班状态
  // 点击到详情的方法，顺便传值 id 过去
  const toDdetails=useCallback(e => {
      handleModalVisible(true)
    }, []);
  //航班号
    const formatFlightNo = (val) => {
      if (!val) {
        return '';
      } else if (val.length < 3 || /^\D/.test(val)) {
        return ''.toUpperCase.call(val);
      } else if (/^\d{2}/.test(val)) {
        return `3U${val}`;
      } else {
        return val;
      }
    }
  // 切换清空搜索
  useEffect(() => {
    hiddenData = null
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // 搜索
  const beforeSearchSubmit = useCallback(params => {

  params['startDate'] = params.startDate ? params.startDate.format('YYYY-MM-DD') : '';
  params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';

  if (!isCollapse) {
    return { ...params }
  } else {
    if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
      if (Object.keys(params).indexOf('startDate') === -1) {
        params.startDate = ''
      }
      if (Object.keys(params).indexOf('endDate') === -1) {
        params.endDate = ''
      }
    } else if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
      hiddenData = {}
    }
    return { ...hiddenData, ...params}
  }
    }, []);

  const columns = [
    {
      title: '航班号',
      dataIndex: 'flightNo',
      width:90,
      fixed: 'left',
      // order:5,
      renderFormItem: (_, { defaultRender, ...rest }) => {
        return <Input onChange={e => {
          e.target.value = formatFlightNo(e.target.value);
        }} {...rest} maxLength={6} placeholder="3U" />;
      }
    },
    {
      title: '航班日期',
      width:120,
      dataIndex: 'flightDate',
      fixed: 'left',
      hideInSearch: true
    },
    {
      title: '航班开始日期',
      hideInTable: true,
      dataIndex: 'startDate',
      order: 8,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      hideInTable: true,
      order: 7,
      dataIndex: 'endDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班状态',
      key: 'flightStatus',
      dataIndex: 'flightStatus',
      showSearch:true,
      fixed: 'left',
      width:120,
      filters: [
        {text: '计划', value: '计划'},
        {text: '起飞', value: '起飞'},
        {text: '到达', value: '到达'},
        {text: '补班', value: '补班'},
        {text: '备降', value: '备降'},
        {text: '返航', value: '返航'},
        {text: '延误', value: '延误'},
        {text: '取消', value: '取消'}
      ],
      valueEnum: {
        '':'全部',
        '计划':'计划',
        '起飞':'起飞',
        '到达' :'到达',
        '补班':'补班',
        '备降':'备降',
        '返航':'返航',
        '延误':'延误',
        '取消':'取消',
      },
    },
    {
      title: '航班类型',
      key: 'flightType',
      dataIndex: 'flightType',
      hideInTable:true,
      width:120,
      filters: [
        {text: '国内', value: 'D'},
        {text: '国际', value: 'I'},
        {text: '地区', value: 'R'}
      ],
      valueEnum: {
        '': '全部',
        'D': '国内',
        'I':'国际',
        'R':'地区'
      },
    },
    {
      title: '航班类型',
      key: 'dorI',
      dataIndex: 'dorI',
      hideInSearch:true,
      width:120,
      filters: [
        {text: '国内', value: 'D'},
        {text: '国际', value: 'I'},
        {text: '地区', value: 'R'}
      ],
      valueEnum: {
        '': '全部',
        'D': '国内',
        'I':'国际',
        'R':'地区'
      },
    },
    {
      // 多个查询选项
      title: '出发航站',
      // hideInTable: true,
      dataIndex: 'departPort',
      width:100,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {
              selectData&&selectData.map((v,i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      }
    },
    {
      // 多个查询选项
      title: '到达航站',
      dataIndex: 'arrivalPort',
      width:100,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {
              selectData&&selectData.map((v,i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      }
    },
    {
      title: '计划起飞时间',
      hideInSearch:true,
      dataIndex: 'std',
      width:130
    },
    {
      title: '计划到达时间',
      hideInSearch:true,
      dataIndex: 'sta',
      width:130
    },
    {
      title: '预计起飞时间',
      hideInSearch:true,
      dataIndex: 'etd',
      width:130
    },
    {
      title: '预计到达时间',
      hideInSearch:true,
      dataIndex: 'eta',
      width:130
    },
    {
      title: '实际起飞时间',
      hideInSearch:true,
      dataIndex: 'atd',
      width:130
    },
    {
      title: '实际到达时间',
      hideInSearch:true,
      dataIndex: 'ata',
      width:130
    },
    {
      title: '旅客总数',
      hideInSearch:true,
      dataIndex: 'bookSeat',
      width:100
    }
  ];
  return (
      <>
      <ProTable
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        size='small'
        className={`${styles.oversaleTable} rest-pro-table-form-compact ${isCollapse?'':'collapse'}`}
        scroll={{ x: 1000, y: height }}
        headerTitle={
          <span style={{paddingRight: 10, fontWeight: "bold", color: "#000"}}>全部航班列表</span>
        }
        search={{
          onCollapse:val => {
            controlC(val);
            if (!val && hiddenData) {
              ref.current.setFieldsValue({
                flightNo:hiddenData.flightNo,
                flightType: hiddenData.flightType,
                flightStatus: hiddenData.flightStatus,
                departPort: hiddenData.departPort,
                arrivalPort: hiddenData.arrivalPort,
              })
            } else {
              hiddenData = ref.current.getFieldsValue()
            }
          }
        }}
        actionRef={actionRef}
        formRef={ref}
        dateFormatter="YYYY-MM-DD"
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        rowKey="key"
        beforeSearchSubmit={beforeSearchSubmit}
        request={params => {
          if (!params['startDate'] && !params['endDate']) {
            params['startDate'] = moment().format('YYYY-MM-DD');
            params['endDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              startDate: moment()
            })
            ref.current.setFieldsValue({
              endDate: moment()
            })
          }
          if (!params['flightNo']) {
            ref.current.setFieldsValue({
              flightNo: ''
            })
          }
          if (!params['flightStatus']) {
            ref.current.setFieldsValue({
              flightStatus: ''
            })
          }
          if (!params['flightType']) {
            ref.current.setFieldsValue({
              flightType: ''
            })
          }
          if (!params['departPort']) {
            ref.current.setFieldsValue({
              departPort: ''
            })
          }
          if (!params['arrivalPort']) {
            ref.current.setFieldsValue({
              arrivalPort: ''
            })
          }
          return queryFlightTable({...params});
        }}
        postData={data => {
          return data.map((v, index) => {
            return {...v, id: index}
          })
        }}
        columns={columns}
        rowSelection={{}}
        onRow={record => {
					return {
						onClick: () => {
              if(AuthComponent.getAuth('flight.index.detail')){
                setflightId(record.flightId)
                setHlightStatus(record.flightStatus)
                toDdetails()
              }
						}
					}
				}}
      />
     {
      createModalVisible&&<ListofDetails
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        flightId={flightId}
        flightStatus={getflightStatus}
      />
     }
      </>
  );
};

export default Form.create()(TableList);
